/**
 * Project oo_thread
 */


#include "../include/RegisterGetcrypt.h"
#include "../include/MySQLConnector.h"
#include "../include/TLVmsg.h"
#include <ctime>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
using std::endl;
using std::cout;
enum TaskType{
    TASK_LOGIN_SECTION1 = 1, 
    TASK_LOGIN_SECTION1_RESP_OK,
    TASK_LOGIN_SECTION1_RESP_ERROR,
    TASK_LOGIN_SECTION2,
    TASK_LOGIN_SECTION2_RESP_OK,
    TASK_LOGIN_SECTION2_RESP_ERROR,
    TASK_TYPE_REGISTER1,
    TASK_TYPE_REGISTER1_RESP_OK,
    TASK_TYPE_REGISTER1_RESP_ERROR,
    TASK_TYPE_GEGISTER2,
    TASK_TYPE_REGISTER2_RESP_OK
};   

/**
 * RegisterTask implementation
 */
RegisterGetcrypt::RegisterGetcrypt(const string msg, TcpConnectionPtr conn)
:_msg(msg)
,_conn(conn)
{

}
std::string RegisterGetcrypt::trim(const std::string& str) {
    size_t first = str.find_first_not_of(" \t\n\r");
    if (first == std::string::npos)
        return "";
    size_t last = str.find_last_not_of(" \t\n\r");
    return str.substr(first, (last - first + 1));
}
bool RegisterGetcrypt::parseAuthString(const std::string& input,
                     std::string& username,
                     std::string& salt,
                     std::string& crypt) {
    // 使用stringstream和getline分割字符串
    std::vector<std::string> parts;
    std::stringstream ss(input);
    std::string part;

    // 按=分割字符串
    while (std::getline(ss, part, '=')) {
        parts.push_back(trim(part));
    }

    // 验证分割结果
    if (parts.size() != 3) {
        return false; // 格式不正确
    }

    // 提取各部分
    username = parts[0];
    salt = parts[1];
    crypt = parts[2];

    return true;
}

/**
 * @return void
 */
void RegisterGetcrypt::process() {

    //handle msg
    cout << "RegisterGetcrypt handle msg" << endl;
    sleep(1);
    MySQLConnector* mysqlconn = MySQLConnector::getInstance();
    cout << "crypt = " << _msg << endl; 
    //密文内格式lwj = salt = crypt
    //解析字符串，并且在数据库内增加新用户
    string username;
    string salt;
    string crypt;
    parseAuthString(_msg, username, salt, crypt);
    cout << "username = " << username << " salt = " << salt << " crypt = " << crypt << endl;
    LOG_WARN("forbit combining sql string, please conrrect later!!");
    string sql = "insert into user (name, setting, encrypt) values ('" +
        username +"','" + salt + "','" + crypt +"')"; 
    cout <<  "sql = " << sql;
    mysqlconn->execute(sql);
    _conn->sendtoLoop(TASK_TYPE_REGISTER2_RESP_OK,"regist success");
}
